<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

const baseUrl = 'http://localhost:8081'
const fileInput = ref(null)
const imageList = ref([])
const loading = ref(false)

// 获取图片列表
const getImageList = async () => {
  try {
    loading.value = true
    const response = await axios.get(baseUrl + '/AI/createimg/list')
    if (response.data.code === 200) {
      imageList.value = response.data.rows
    } else {
      throw new Error(response.data.msg || '获取图片列表失败')
    }
  } catch (error) {
    console.error('获取图片列表失败:', error)
    ElMessage.error(error.message || '获取图片列表失败')
  } finally {
    loading.value = false
  }
}

// 生成唯一的文件名
const generateUniqueFileName = () => {
  const timestamp = new Date().getTime()
  const random = Math.floor(Math.random() * 10000)
  return `upload_${timestamp}_${random}`
}

// 处理文件上传
const handleFiles = async (files) => {
  for (const file of files) {
    if (!file.type.startsWith('image/')) {
      ElMessage.warning(`${file.name} 不是有效的图片文件`)
      continue
    }

    try {
      // 创建 FormData
      const formData = new FormData()
      formData.append('file', file)
      
      // 上传文件
      const uploadResponse = await axios.post(baseUrl + '/common/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      
      if (uploadResponse.data.code === 200) {
        // 创建图片记录
        const requestData = {
          createimgName: file.name,
          createimgUrl: uploadResponse.data.url
        }
        
        const response = await axios.post(baseUrl + '/AI/createimg', requestData)
        
        if (response.data.code === 200) {
          ElMessage.success('上传成功')
          getImageList() // 刷新图片列表
        } else {
          throw new Error(response.data.msg || '创建图片记录失败')
        }
      } else {
        throw new Error(uploadResponse.data.msg || '文件上传失败')
      }
    } catch (error) {
      console.error('上传失败:', error)
      ElMessage.error(error.message || '上传失败')
    }
  }
}

// 删除图片
const handleDelete = async (createimgId) => {
  try {
    await ElMessageBox.confirm('确认要删除这张图片吗？', '提示', {
      type: 'warning'
    })
    
    const response = await axios.delete(baseUrl + `/AI/createimg/${createimgId}`)
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      getImageList() // 刷新图片列表
    } else {
      throw new Error(response.data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value.click()
}

// 处理文件选择
const handleFileChange = (event) => {
  const files = event.target.files
  handleFiles(files)
}

// 处理拖拽
const handleDrop = (event) => {
  const files = event.dataTransfer.files
  handleFiles(files)
}

// 下载图片
const downloadImage = (image) => {
  const link = document.createElement('a')
  link.href = image.createimgUrl
  link.download = image.createimgName
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString()
}

// 页面加载时获取图片列表
onMounted(() => {
  getImageList()
})
</script>

<template>
  <div class="upload-container">
    <!-- 上传区域 -->
    <div class="upload-section">
      <h2>上传作品</h2>
      <div class="upload-box" @click="triggerFileInput" @drop.prevent="handleDrop" @dragover.prevent>
        <input 
          type="file" 
          ref="fileInput" 
          @change="handleFileChange" 
          accept="image/*" 
          multiple 
          style="display: none"
        >
        <div class="upload-hint">
          <i class="upload-icon">📁</i>
          <p>点击或拖拽图片到此处上传</p>
          <span class="upload-tip">支持 jpg、png、gif 格式</span>
        </div>
      </div>
    </div>

    <!-- 图片展示区域 -->
    <div class="gallery-section">
      <h2>作品展示</h2>
      <div class="gallery-grid">
        <div v-for="(image, index) in imageList" :key="image.createimgId" class="image-card">
          <div class="image-wrapper">
            <el-image 
              :src="image.createimgUrl"
              :preview-src-list="[image.createimgUrl]"
              preview-teleported
              fit="cover"
              class="gallery-image"
            />
            <div class="image-overlay">
              <div class="image-info">
                <h3>{{ image.createimgName }}</h3>
                <p>{{ formatDate(image.createTime) }}</p>
              </div>
              <div class="image-actions">
                <button @click.stop="downloadImage(image)">下载</button>
                <button @click.stop="handleDelete(image.createimgId)" class="delete">删除</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.upload-container {
  padding: 2rem;
  max-width: 1400px;
  margin: 0 auto;
}

.upload-section {
  margin-bottom: 3rem;
}

.upload-box {
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 2rem;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #f9f9f9;
}

.upload-box:hover {
  border-color: #7B66FF;
  background: #f5f5f5;
}

.upload-hint {
  color: #666;
}

.upload-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.upload-tip {
  font-size: 0.9rem;
  color: #999;
  margin-top: 0.5rem;
  display: block;
}

.gallery-section h2 {
  margin-bottom: 2rem;
}

.gallery-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 2rem;
}

.image-card {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.image-card:hover {
  transform: translateY(-5px);
}

.image-wrapper {
  position: relative;
  padding-bottom: 100%;
}

.image-wrapper img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 1rem;
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: 1;
}

.image-wrapper:hover .image-overlay {
  opacity: 1;
}

.image-info {
  color: white;
}

.image-info h3 {
  margin: 0;
  font-size: 1.2rem;
}

.image-info p {
  margin: 0.5rem 0 0;
  font-size: 0.9rem;
  opacity: 0.8;
}

.image-actions {
  display: flex;
  gap: 1rem;
  position: relative;
  z-index: 2;
}

.image-actions button {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  background: white;
  color: #333;
  transition: all 0.3s ease;
}

.image-actions button.delete {
  background: #ff4444;
  color: white;
}

.image-actions button:hover {
  opacity: 0.9;
}

@media (max-width: 768px) {
  .upload-container {
    padding: 1rem;
  }

  .gallery-grid {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 1rem;
  }
}

.gallery-image {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}

/* 确保预览组件显示在最上层 */
:deep(.el-image-viewer__wrapper) {
  position: fixed;
  z-index: 2100;
}

:deep(.el-image-viewer__btn) {
  opacity: 0.8;
  color: #fff;
  font-size: 44px;
}

:deep(.el-image-viewer__prev) {
  left: 40px;
}

:deep(.el-image-viewer__next) {
  right: 40px;
}

:deep(.el-image-viewer__actions) {
  opacity: 0.8;
  padding: 20px;
}

:deep(.el-image-viewer__actions__inner) {
  padding: 6px 15px;
}

:deep(.el-image-viewer__close) {
  top: 40px;
  right: 40px;
}

/* 添加阻止事件冒泡 */
.image-actions button {
  position: relative;
  z-index: 2;
}

/* 修改图片样式 */
:deep(.el-image) {
  width: 100%;
  height: 100%;
}

:deep(.el-image__inner) {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 添加错误状态样式 */
.image-error {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #909399;
  font-size: 14px;
}
</style>